package com.kobi.tapeRecorder;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.text.format.DateFormat;



public class RecordService extends Service {

	public static final String FILE_DIRECTORY = "recordedTape";
	private MediaRecorder recorder = new MediaRecorder();
	
	private NotificationManager manger;
	private Messenger messenger;
	
	private Timer timer = new Timer();
	
	
	
	class RecordLimitTimerTask extends TimerTask 
	{

		@Override
		public void run() {
			recordStop(true);
			
		}
		
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		int commandType = intent.getIntExtra("commandType", MainActivity.RECORD_START);
		int timeLimit = intent.getIntExtra(MainActivity.RECORD_LENGTH, MainActivity.RECORD_START);
		Bundle extras = intent.getExtras();
		messenger = (Messenger) extras.get("MESSENGER");
		
		if (commandType == MainActivity.RECORD_START)
		{
			recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
			recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			recorder.setOutputFile(getFilename());
			
			OnErrorListener errorListener = null;
			recorder.setOnErrorListener(errorListener);
			OnInfoListener infoListener = null;
			recorder.setOnInfoListener(infoListener);
			
			try {
				recorder.prepare();
				recorder.start();
				
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			manger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
	    	Notification notification = new Notification(R.drawable.ic_launcher, this.getString(R.string.notification_ticker), System.currentTimeMillis());
	    	notification.flags = Notification.FLAG_NO_CLEAR;
	    	
	    	Intent intent2 = new Intent(this, MainActivity.class);
	    	intent2.putExtra("RecordStatus", true);

	        PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(), 0, intent2, 0);
	        notification.setLatestEventInfo(this, this.getString(R.string.notification_title), this.getString(R.string.notification_text), contentIntent);
	        manger.notify(0, notification);
	        
	        if (timeLimit != MainActivity.RADIO_NONE)
	        {
		        timeLimit = timeLimit * 60 * 1000;
	        	TimerTask updateBall = new RecordLimitTimerTask();
		        timer.schedule(updateBall, timeLimit);
	        }
		}
		else if (commandType == MainActivity.RECORD_END)
		{
			recordStop(false);
		}
		
		return super.onStartCommand(intent, flags, startId);
	}
	
	
	
	/**
	 * stops the recording process
	 */
	private void recordStop(boolean message)
	{
		try {
			//recorder.stop();
			//recorder.reset();
			//recorder.release();
			recorder = null;
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
		
		manger.cancel(0);
		
		if (message)
		{
			Message msg = Message.obtain();
			msg.arg1 = Activity.RESULT_OK;
		    try {
		    	messenger.send(msg);
		    } 
		    catch (android.os.RemoteException e1) {
		        
		    }
		}
		
		this.stopSelf();
	}
	
	/**
	 * returns absolute file directory
	 * 
	 * @return
	 */
	private String getFilename() {
		String filepath = Environment.getExternalStorageDirectory().getPath();
		File file = new File(filepath, FILE_DIRECTORY);

		if (!file.exists()) {
			file.mkdirs();
		}
		
		String myDate = new String();
		myDate = (String) DateFormat.format("yyyyMMddkkmmss", new Date());

		return (file.getAbsolutePath() + "/d" + myDate + ".mp3");
	}

}
